import Taro from '@tarojs/taro';
import { useCallback, useEffect, useState } from 'react';

function useStorage(key, defaultValue) {
  const [value, setValue] = useState(defaultValue);

  const getValue = useCallback(async () => {
    return Taro.getStorage({ key })
      .then((v) => {
        setValue(v?.data);
      })
      .catch((e) => {
        console.warn(e, key);
      });
  }, [key]);

  // 初始化获取
  useEffect(() => {
    getValue();
  }, []);

  const setStorage = async (data) => {
    setValue(data);
    await Taro.setStorage({ key, data });
  };

  return [value, setStorage];
}

export default useStorage;
